package com.bird.framework.security.handle;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.bird.common.constant.Constants;
import com.bird.common.utils.ServletUtil;
import com.bird.framework.domain.Result;
import com.bird.framework.security.service.TokenService;
import com.bird.framework.thread.AsyncManager;
import com.bird.framework.thread.factory.AsyncFactory;
import com.bird.system.domain.bo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 * @author bird
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

	@Autowired
	private TokenService tokenService;

	/**
	 * 退出处理
	 *
	 * @return
	 */
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		LoginUser loginUser = tokenService.getLoginUser(request);
		if (ObjectUtil.isNotNull(loginUser)) {
			String userName = loginUser.getUsername();
			// 删除用户缓存记录
			tokenService.delLoginUser(loginUser.getToken(), loginUser.getLoginType().getKey());
			// 记录用户退出日志
			AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, loginUser.getLoginType(), Constants.System.LOGOUT, "退出成功"));
		}
		ServletUtil.write(response, JSON.toJSONString(Result.ok("退出成功")), MediaType.APPLICATION_JSON_UTF8_VALUE);
	}
}
